
import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import styles from './index.module.less';
import Account from './component/Account';
import Mobile from './component/Mobile';
import WxRelative from './component/WxRelative';
import PreLoginCheck from './component/PreLoginCheck';
import SelectLoginAccount from './component/CustomModal';
import { Tabs } from 'antd';
import Iconfont from '@/components/IconFont';
import CommonLoading from '@/components/CommonLoading';
import { setAuthMsg, removeAll } from '@/utils/authority';
import { renderRoleType, getSearchParamsObj } from '@/utils/utils.jsx';
import { getWxLoginParamsOp, getAccountListByUnionIdOp, getAccountListByMobileOp } from './service';
import useLoginStore from './loginStore.js';

const { TabPane } = Tabs;

let wxAuthParams = {};

const Login = () => {

	const loginInfo = useLoginStore(state => state.loginInfo);

	const checkInfo = useLoginStore(state => state.checkInfo);

	const type = useLoginStore(state => state.type);
	
	const loading = useLoginStore(state => state.loading);

	const switchType = useLoginStore(state => state.switchType);

	const newPreLogin = useLoginStore(state => state.newPreLogin);

	const updateLoginInfo = useLoginStore(state => state.updateLoginInfo);


  const [activeKey, setActiveKey] = useState('1');
  const [updateKey, setUpdateKey] = useState(0);

  const [userList, setUserList] = useState([]);

  const location = useLocation();

	const navigate = useNavigate();

  const stageParams = useRef(null);

  const onChange = (val) => {//tab变化事件
		switchType(val);
  }

  useEffect(() => {
    if (window.zc) {
      window.zc = null;
      removeAll();
      window.location.reload();
      return;
    }

		updateLoginInfo({
			...loginInfo,
			username: location.state?.account,
			password: location.state?.password,
		})

    if (location.search) {
      const obj = getSearchParamsObj(location.search);
      if (obj.authCode && obj.authState){
        setAuthMsg({
          authCode: obj.authCode,
          authState: obj.authState,
        })
        navigate('/user/login', { replace: true });
      }
      if(obj.unionid){//来源为微信登录重定向
        if(obj.type == 1){//去登录
          getUserListFunc({ unionid: obj.unionid });
        }else{//去绑定
          handleJump();
        }
      }
    }
    if (renderRoleType() == 'daifa') {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?1f6fb9676e30de0f0371cfe961f72123";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    }
    getWxAuthParams();
  }, [])

  //获取微信授权参数
  const getWxAuthParams = async () => {
    const { data, success } = await getWxLoginParamsOp({ industrialBeltFlag: INDUSTRIAL_BELT_FLAG });
    if(success){
      wxAuthParams = data || {};
    }
   }

  //获取用户列表(unionid)
  const getUserListFunc = async ({ unionid, mobile, sms_code }) => {
    let res;
    if(sms_code){//验证码登录
      res = await getAccountListByMobileOp({ mobile, code: sms_code, industrialBeltFlag: INDUSTRIAL_BELT_FLAG });
    }else{//微信登录
      res = await getAccountListByUnionIdOp({ unionid, industrialBeltFlag: INDUSTRIAL_BELT_FLAG });
    }
    const { data, success } = res;
    if(success && data){
      const { userList, codeKey } = data;
      if(userList?.length > 1){//选择用户
        stageParams.current = {
          ...stageParams.current,
          unionid,
          mobile,
          sms_code,
          codeKey,
        }
        setUserList(userList);
      }else if(userList?.length == 1){//准备风控认证
				newPreLogin({
					unionid,
					mobile,
					sms_code,
					codeKey,
					userId: userList[0]?.id
				})
      }
    }
  }

  const AccountProps = {
    loginInfo,
  }

  const MobileProps = {
    loginInfo,
    handleBindBack: getUserListFunc
  }

  const PreLoginCheckProps = {
    checkInfo,
  }

  const wxRelativeProps = {
    location,
    updateKey,
    wxAuthParams,
    handleBack(){
      setActiveKey('1');
    },
    handleBindBack: getUserListFunc
  }

  const selectAccountModal = {
    userList,
    handleOk(obj){
      setUserList([]);
			newPreLogin({
				...stageParams.current,
				userId: obj.id
			})
    },
    handleCancel(){
      setUserList([]);
    }
  }

  const handleJump = () => {
    setActiveKey('2');
    setUpdateKey(updateKey + 1);
  }

  return (
    <>
      <div className={styles.main}>
        <Tabs
          renderTabBar={() => null}
          activeKey={activeKey}
          items={[
            {
              key: '1',
              children: (<><Tabs activeKey={type} onChange={onChange} centered style={{ textAlign: 'center' }}>
                <TabPane tab="账号密码登录" key="account">
                  <Account {...AccountProps} />
                </TabPane>
                <TabPane tab="手机号登录" key="mobile">
                  <Mobile {...MobileProps} />
                </TabPane>
              </Tabs>
                <div className={styles.otherLoginType}>
                  <p>其它方式登录</p>
                  <span onClick={handleJump}>
                    <span>
                      <Iconfont type='iconweixin2' className={styles.vxIcon} />
                    </span>
                    <p className='common-color2'>微信</p>
                  </span>
                </div>
              </>),
            },
            {
              key: '2',
              children: <WxRelative {...wxRelativeProps} />,
            },
          ]}
        />
      </div>
      <PreLoginCheck {...PreLoginCheckProps} />
      { !!userList?.length && <SelectLoginAccount {...selectAccountModal} /> }
      
      <CommonLoading loading={loading} />
    </>
  );
};

export default Login;